package com.qianguo.buyer;


import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.eva.androidlibrary.api.HttpRequestCallback;
import com.eva.androidlibrary.api.entity.ShopInfo;
import com.eva.androidlibrary.api.entity.ShopListBean;
import com.eva.androidlibrary.icon.FruitIcon;
import com.eva.androidlibrary.utils.DevUtil;
import com.eva.androidlibrary.utils.IconfontUtil;
import com.eva.androidlibrary.widget.tabhost.FragmentTabHostLayout;
import com.eva.androidlibrary.widget.tabhost.FragmentTabHostLayoutAdapter;
import com.eva.androidlibrary.widget.tabhost.TabHostLayout;
import com.eva.baidulibrary.BDLocationClient;
import com.eva.baidulibrary.BDMapClient;
import com.eva.baidulibrary.BaiduZoomLevel;
import com.qianguo.buyer.base.BaseNoTitleActivity;
import com.qianguo.buyer.entity.ShopMarker;
import com.qianguo.buyer.tab.BuyerProfileFragment_;
import com.qianguo.buyer.tab.CopyBuyerOrderFragment_;
import com.qianguo.buyer.tab.ShopCartFragment_;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 买家首页
 *
 * @author eva
 */
@EActivity(R.layout.activity_buyer_main)
public class BuyerMainActivity extends BaseNoTitleActivity {

    private static final int M_SDK_PERMISSION_REQUEST = 1010;

    private static final int TAB_MAIN = 0;
    private static final int TAB_SHOP_CART = 1;
    private static final int TAB_ORDER = 2;
    private static final int TAB_PROFILE = 3;

    private static final int[] TABS_NAME = new int[] {R.string.tab_main, R.string.tab_shop_cart, R.string.tab_order, R.string.tab_profile};
    private static final FruitIcon[] TABS_ICON = new FruitIcon[] {FruitIcon.TAB_MAIN, FruitIcon.ICON_SHOP_CART, FruitIcon.TAB_ORDER, FruitIcon.TAB_MY_CENTER};
    private static final FruitIcon[] TABS_ICON_SELECTED = new FruitIcon[] {FruitIcon.TAB_MAIN_SELECTED, FruitIcon.ICON_SHOP_CART_SELECTED, FruitIcon.TAB_ORDER, FruitIcon.TAB_MY_CENTER_SELECTED};

    @ViewById(R.id.fragment_container)
    FrameLayout mTabFragment;
    @ViewById(R.id.fragment_tab_host_layout)
    FragmentTabHostLayout mFragmentTabHostLayout;
    private FragmentTabHostLayoutAdapter mAdapter;

    private static final float DEFAULT_ZOOM_LEVEL = BaiduZoomLevel.LEVEL_200_METER;
    private static final int DEFAULT_RADIUS = 1000;

    @ViewById(R.id.buyer_main_layout)
    LinearLayout mMainLayout;

    @ViewById(R.id.buyer_map_view)
    MapView mMapView;


    @ViewById(R.id.buyer_current_location_text_view)
    TextView mTvLocation;

    @ViewById(R.id.buyer_current_location_icon_text_view)
    TextView mCurrentLocationIcon;

    private BaiduMap mBaiduMap;
    private BDLocationClient mBDLocationClient = BDLocationClient.getInstance();
    private BDMapClient mMapClient = BDMapClient.getInstance();
    private Map<String, ShopMarker> markers = new HashMap<>();
    private BDLocation mCurrentLocation;

    public static void jumpToMain(Context context) {
        context.startActivity(new Intent(context, BuyerMainActivity_.class));
    }
    
    @Override
    protected void initializeUI() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<>();

            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }

            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), M_SDK_PERMISSION_REQUEST);
            }
        }

        IconfontUtil.setIcon(this, mCurrentLocationIcon, FruitIcon.ICON_ARROW_DOWN);
        mAdapter = new TabHostAdapter(R.id.fragment_container, getSupportFragmentManager());
        mFragmentTabHostLayout.setAdapter(mAdapter);
        mFragmentTabHostLayout.setTabSelected(0);
        mFragmentTabHostLayout.setOnTabHostItemSelectedListener(new TabHostLayout.OnTabHostSelectedChangedListener() {
            @Override
            public void onSelected(View view, int position) {
                if (position == TAB_MAIN) {
                    mMainLayout.setVisibility(View.VISIBLE);
                } else {
                    mMainLayout.setVisibility(View.GONE);
                }
            }
        });
        initMap();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == M_SDK_PERMISSION_REQUEST) {
            // TODO: 16/9/7  
        }
    }

    private void initMap() {
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        // 开启定位图层
        mMapClient.openMyLocation(mBaiduMap, 0);
        mBDLocationClient.requestLocation(this, new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                if (location != null) {

                    StringBuffer sb = new StringBuffer();
                    sb.append("latitude: ");
                    sb.append(Double.toString(location.getLatitude()) + "\n");
                    sb.append("longitude: ");
                    sb.append(Double.toString(location.getLongitude()) + "\n");
                    DevUtil.v("Eva", sb.toString());

                    updateLocation(location);
                    // 显示当前位置
                    mMapClient.showMyLocation(mBaiduMap, location, DEFAULT_ZOOM_LEVEL);
                    getNearByShops(location);
                }
            }
        });

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                // 跳转到店铺
                ShopInfo shop = markers.get(marker.getPosition().toString()).getShop();
                BuyerProductListActivity.jumpToProductList(BuyerMainActivity.this, shop);
//                ShopFruitListActivity.jumpToShop(BuyerMainActivity.this, shop);
                return true;
            }
        });
    }

    private void updateLocation(BDLocation location) {
        mCurrentLocation = location;
        final List<Poi> poiList = location.getPoiList();
        if (poiList != null && poiList.size() > 0) {
            Poi poi = poiList.get(0);
            mTvLocation.setText(poi.getName());
        } else {
            mTvLocation.setText(location.getAddrStr());
        }
    }

    /**
     * 获取周边店铺
     *
     * @param location
     */
    @Background
    void getNearByShops(BDLocation location) {
        String center = Double.toString(location.getLongitude()) + "," + Double.toString(location.getLatitude());
        mApp.getApi().getNearByShop(1, 10, center, 1, new HttpRequestCallback<ShopListBean>() {
            @Override
            public void onSuccess(int code, String msg, ShopListBean data) {
                showNearByShop(data.getList());
            }

            @Override
            public void onFailure(int code, String msg) {
                showSnackBar(BuyerMainActivity.this, msg);
            }
        });
    }

    @UiThread
    void showNearByShop(List<ShopInfo> list) {
        for (int i = 0; i < list.size(); i++) {
            addShopMarker(list.get(i));
        }
    }

    /**
     * 标注覆盖物
     *
     */
    private void addShopMarker(ShopInfo shop) {
        // 定义Marker坐标点
        LatLng point = new LatLng(Double.parseDouble(shop.getLatitude()), Double.parseDouble(shop.getLongitude()));
        // TODO: 16/6/28 后面加上是否在屏幕内判断
        if (!markers.containsKey(point.toString())) {
            // 构建Marker图标
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.ic_map_marker);
            // 构建MarkerOption，用于在地图上添加Marker
            OverlayOptions option = new MarkerOptions().position(point).icon(bitmap);
            // 在地图上添加Marker，并显示
            Marker marker = (Marker) mBaiduMap.addOverlay(option);
            ShopMarker shopMarker = new ShopMarker();
            shopMarker.setMarker(marker);
            shopMarker.setShop(shop);
            markers.put(point.toString(), shopMarker);
        }
    }

    /**
     * 判断经纬度是否在当前屏幕内
     *
     * @param latlng
     * @return
     */
    private boolean isInScreen(LatLng latlng) {
        Point point = mBaiduMap.getProjection().toScreenLocation(latlng);
        final DisplayMetrics dm = getResources().getDisplayMetrics();
        Rect screenRect = new Rect(0, 0, dm.widthPixels, dm.heightPixels);
        return screenRect.contains(point.x, point.y);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }

    private class TabHostAdapter extends FragmentTabHostLayoutAdapter {

        public TabHostAdapter(int containerId, FragmentManager fm) {
            super(containerId, fm);
        }

        @Override
        public int getCount() {
            return TABS_NAME.length;
        }

        @Override
        public View getTab(int position, boolean isSelected, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(BuyerMainActivity.this).inflate(R.layout.activity_tab_business, null);
            }

            TextView icon = (TextView) convertView.findViewById(R.id.business_tab_icon);
            if (isSelected) {
                IconfontUtil.setIcon(BuyerMainActivity.this, icon, TABS_ICON_SELECTED[position]);
            } else {
                IconfontUtil.setIcon(BuyerMainActivity.this, icon, TABS_ICON[position]);
            }

            TextView name = (TextView) convertView.findViewById(R.id.business_tab_text);
            name.setText(getString(TABS_NAME[position]));
            return convertView;
        }

        @Override
        public Fragment getFragmentInstance(int position) {
            Fragment f = null;
            switch (position) {
                case TAB_SHOP_CART:
                    f = new ShopCartFragment_();
                    break;
                case TAB_ORDER:
                    f = new CopyBuyerOrderFragment_();
                    break;
                case TAB_PROFILE:
                    f = new BuyerProfileFragment_();
                    break;
            }
            return f;
        }
    }

}
